package com.itqf.controller;

import com.itqf.bean.Permission;
import com.itqf.bean.User;
import com.itqf.mapper.PermissionMapper;
import com.itqf.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * projectName: rbac2103
 *
 * @author: 赵伟风
 * time: 2021/7/8 11:36
 * description:用户登录和权限展示的controller
 */

@Controller
@RequestMapping("user")
@SessionAttributes(names = {"ret"})
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionMapper permissionMapper;


    @GetMapping("index")
    public String indexHtml(){
        return "index";
    }


    @GetMapping("logout")
    public String logout(SessionStatus sessionStatus){

        //清空数据
        sessionStatus.setComplete();

        return "login";
    }

    @GetMapping("html")
    public String loginHtml(){
        System.out.println("跳转登录页面!");

        return "login";
    }

    @PostMapping("login")
    public ModelAndView login(User user){
        //没有实体类
        ModelAndView modelAndView = new ModelAndView();

        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(user.getuAccount(), user.getuPassword());

        try {

            subject.login(token);

        }catch (AuthenticationException e)
        {

            modelAndView.setViewName("login");
            return modelAndView;
        }

        User usernew = (User) subject.getPrincipal();


        List<Permission> permissions =  permissionMapper.query(usernew.getuId());
        //3.
        Map map = new HashMap();
        map.put("code", 1);
        map.put("user", usernew);
        map.put("permission", permissions);


        modelAndView.addObject("ret", map);
        modelAndView.setViewName("index");

        return modelAndView;
    }


    /**
     * 未认证
     * @return
     */
    @GetMapping("noauthentication")
    public String noauthentication(){

        return "noauthentication";
    }


    /**
     * 未授权
     * @return
     */
    @GetMapping("noauthorization")
    public String noauthorization(){

        return "noauthorization";
    }
}
